package org.yan.kangaroo.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.yan.kangaroo.common.constant.WebRequestHeaderConstants;
import org.yan.kangaroo.common.threadlocal.GlobalRequestIdThreadLocal;
import org.yan.kangaroo.common.util.McpStringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangx
 * @date 12/02/2019 13:53
 */
@Configuration
@Slf4j
public class GlobalInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("[preHandle] requestURI:{},method:{},queryString:{}", request.getRequestURI(), request.getMethod(), request.getQueryString());

        String requestId = request.getHeader(WebRequestHeaderConstants.REQUEST_ID);
        if (StringUtils.isBlank(requestId)) {
            requestId = McpStringUtils.getRequestId();
        }
        GlobalRequestIdThreadLocal.setRequestId(requestId);
        MDC.put(WebRequestHeaderConstants.REQUEST_ID, requestId);
        log.debug("[preHandle] requestId:{}", requestId);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("[postHandle] 释放资源");
        GlobalRequestIdThreadLocal.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
